package com.examplemartin.jpademo.controller.stock.sell;

import com.examplemartin.jpademo.bean.AjaxResult;
import com.examplemartin.jpademo.pojo.po.UserPO;
import com.examplemartin.jpademo.pojo.po.cust.CustPO;
import com.examplemartin.jpademo.pojo.po.repository.sell.SellOutDetailPO;
import com.examplemartin.jpademo.pojo.po.repository.sell.SellOutPO;
import com.examplemartin.jpademo.pojo.po.sell.SellDetailPO;
import com.examplemartin.jpademo.pojo.po.sell.SellPO;
import com.examplemartin.jpademo.pojo.po.stock.RepoInfoPO;
import com.examplemartin.jpademo.pojo.po.stock.StockPO;
import com.examplemartin.jpademo.pojo.vo.purchase.SellDetailVO;
import com.examplemartin.jpademo.pojo.vo.purchase.SellVOForSellout;
import com.examplemartin.jpademo.service.CustService;
import com.examplemartin.jpademo.service.RepoInfoService;
import com.examplemartin.jpademo.service.UserService;
import com.examplemartin.jpademo.service.sell.SellService;
import com.examplemartin.jpademo.service.sellout.SellOutService;
import com.examplemartin.jpademo.util.SessionUtil;
import com.examplemartin.jpademo.util.ValidateMember;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RequestMapping("/sellout")
@Controller
public class SellOutController {
    @Resource
    private SellOutService sellOutService;

    @Resource
    private CustService custService;
    @Resource
    private SellService sellService;
    @Resource
    private UserService userService;

    /**
     * selloutstock.do跳转到销售出库单列表界面
     */
    // 模糊查询还没做
    @GetMapping("/selloutstock.do")
    public String purinstockDo(
            @RequestParam(name = "sellname", required = false) String sellname,
            @RequestParam(name = "outname", required = false) String outname,
            @RequestParam(name = "statusid", required = false) String statusid,
            @RequestParam(name = "custid", required = false) String custid,
            Model model
    ) {
        model.addAttribute("title", "销售出库单");

        Integer stuatus = null;
        if (!ValidateMember.isEmpty(statusid)) {
            stuatus = Integer.valueOf(statusid);
        } else {
            stuatus = null;
        }

        Long cust = null;
        if (!ValidateMember.isEmpty(custid)) {
            cust = Long.valueOf(custid);
        } else {
            cust = null;
        }

        if (ValidateMember.isEmpty(sellname)) {
            sellname = null;
        }

        if (ValidateMember.isEmpty(outname)) {
            outname = null;
        }



        List<SellOutPO> all = sellOutService.findAll();

        model.addAttribute("selloutlist", all);
        model.addAttribute("selloutstatus", SellOutService.SELLOUT_STATUS_MAP);

        List<CustPO> allcust = custService.findAll();


        model.addAttribute("custlist", allcust);

        return "stock/sell/selloutstocklist";
    }

    @Resource
    private RepoInfoService repoInfoService;
    /**
     * /newSellOut.do 跳转到 新建销售出库单 界面
     */
    @GetMapping("/newSellOut.do")
    public String newSellOutDo(Model model,
                               @RequestParam(name = "sellid", required = false) Long sellid) {
        model.addAttribute("title", "新建销售出库单");

        // 获取执行中的 销售订单
        List<SellPO> running = sellService.findByStatus(SellService.SELL_STATUS_RUNNING);
        //商品名称	商品型号	商品规格	计划采购量	已入库	到货量

        ArrayList<SellVOForSellout> sellVO = new ArrayList<>();

        for (SellPO po : running) {
            SellVOForSellout vo = new SellVOForSellout();
            vo.setStatus(po.getStatus());
            vo.setId(po.getId());
            vo.setComment(po.getComment());
            vo.setName(po.getName());
            vo.setCustPO(po.getCustPO());
            vo.setUserPO(po.getUserPO());

            vo.setNeed(po.getNeed());
            vo.setCreateTime(po.getCreateTime());
            vo.setUpdateTime(po.getUpdateTime());

            vo.setSellDetailVOList(new ArrayList<SellDetailVO>());
            List<SellDetailPO> podetaillist = po.getSellDetailPOList();
            // 01 填充 销售商品信息 -- 初始化
            HashMap<Long, Integer> goodmap = new HashMap<>();
            for (SellDetailPO detailPO : podetaillist) {
                goodmap.put(detailPO.getGoodPO().getId(), 0);
                SellDetailVO sellDetailVO = new SellDetailVO();
                sellDetailVO.setGoodPO(detailPO.getGoodPO());
                sellDetailVO.setGoodcount(detailPO.getGoodcount());
                vo.getSellDetailVOList().add(sellDetailVO);
            }
            // 02 统计已出库数量 更新数量
            List<SellOutPO> sellOutPOList = po.getSellOutPOList();
            for (SellOutPO sellOutPO : sellOutPOList) {
                List<SellOutDetailPO> sellOutDetailPOList = sellOutPO.getSellOutDetailPOList();
                for (SellOutDetailPO sellOutDetailPO : sellOutDetailPOList) {
                    Long goodid = sellOutDetailPO.getGoodPO().getId();
                    Integer goodcount = sellOutDetailPO.getGoodcount();
                    Integer been = goodmap.get(goodid);
                    goodmap.put(goodid, been + goodcount);
                }
            }

            for (SellDetailVO sellDetailVO : vo.getSellDetailVOList()) {
                sellDetailVO.setOutStockCount(goodmap.get(sellDetailVO.getGoodPO().getId()));
            }

            sellVO.add(vo);

        }

        UserPO loninUser = SessionUtil.getLoninUser();
        StockPO stockPO = loninUser.getStockPO();
        List<RepoInfoPO> allByStockPO = repoInfoService.findAllByStockPO(stockPO);

        HashMap<Long, Integer> repomap = new HashMap<>();
        for (RepoInfoPO repoInfoPO : allByStockPO) {
            repomap.put(repoInfoPO.getGoodPO().getId(),repoInfoPO.getGoodcount());
        }

        model.addAttribute("repomap", repomap);

        model.addAttribute("selllist", sellVO);

        return "stock/sell/newSellOut";
    }

    /**
     * 新建销售出库单 -- 包括明细
     */
    @PostMapping("/savesellout.ajax")
    @ResponseBody
    public AjaxResult saveselloutAjax(@RequestBody SellOutPO sellOutPO) {

        UserPO loninUser = SessionUtil.getLoninUser();
        UserPO userById = userService.findUserById(loninUser.getId());
        sellOutPO.setUserPO(userById);

        // purInPO 交付 server 处理

        AjaxResult result = sellOutService.newSellOut(sellOutPO);




        return result;
        /*if (result.getCode() != 200) {
            return AjaxResult.fail(result.getCode(), result.getMsg());
        } else {
            PurInPO newpurInPO = (PurInPO) result.getData().get("purInPO");
            return AjaxResult.success(200, newpurInPO.getName() + ": 入库单保存成功", null);
        }*/

        // 更新库存
        /*List<PurInDetailPO> purInDetailPOList = save.getPurInDetailPOList();
        for (PurInDetailPO purInDetailPO : purInDetailPOList) {
            GoodPO goodPO = purInDetailPO.getGoodPO();
            Integer count = purInDetailPO.getGoodcount();
            RepoInfoPO repoInfoPO = new RepoInfoPO();

            // 获取用户关联的仓库
            StockPO stockbyId = stockService.findById(userById.getStockPO().getId());

            // 设定入库数量
            repoInfoPO.setGoodcount(count);


            // 查询 -- 根据商品和仓库
            List<RepoInfoPO> allByStockPOAndGoodPO = repoInfoService.findAllByStockPOAndGoodPO(stockbyId, goodPO);

            if (allByStockPOAndGoodPO == null || allByStockPOAndGoodPO.size() <= 0) // 仓储没有条目, 新建
            {
                // 设定商品
                repoInfoPO.setGoodPO(goodPO);
                // 设定仓库
                repoInfoPO.setStockPO(stockbyId);

                RepoInfoPO ret = repoInfoService.save(repoInfoPO);
                if (ret == null) {
                    return AjaxResult.success(200, "入库单保存成功", null);
                } else {
                    return AjaxResult.fail(500, "入库单保存失败");
                }
            }

            if (allByStockPOAndGoodPO.size() > 1) // 仓储有冲突
            {
                return AjaxResult.fail(500, "仓储条目有冲突");
            }

            if (allByStockPOAndGoodPO.size() == 1) {
                RepoInfoPO repoInfoPO1 = allByStockPOAndGoodPO.get(0);
                repoInfoPO1.setGoodcount(repoInfoPO1.getGoodcount() + count);
                RepoInfoPO ret = repoInfoService.save(repoInfoPO1);
                if (ret == null) {
                    return AjaxResult.fail(500, "入库单保存失败");
                }
            }
        }*/

    }


    /**
     * 编辑销售出库单
     */
    @GetMapping("/editsellout.do")
    public String editselloutDo(Long id, Model model) throws CloneNotSupportedException {
        model.addAttribute("title", "编辑销售出库单");

//        PurInPO purInPO = purInService.editpurinDo(id);
        SellOutPO sellOutPO=sellOutService.editselloutDo(id);

        model.addAttribute("sellOut", sellOutPO);

        List<RepoInfoPO> allByStockPO = repoInfoService.findAllByStockPO(sellOutPO.getUserPO().getStockPO());

        HashMap<Long, Integer> repomap = new HashMap<>();
        for (RepoInfoPO repoInfoPO : allByStockPO) {
            repomap.put(repoInfoPO.getGoodPO().getId(),repoInfoPO.getGoodcount());
        }

        model.addAttribute("repomap", repomap);

        return "stock/sell/editSellOut";
    }

    /**
     * 保存修改的出库单 /editsellout.ajax
     */
    @PostMapping("/editsellout.ajax")
    @ResponseBody
    public AjaxResult editselloutAjax(@RequestBody SellOutPO sellOutPO) {

        AjaxResult result = sellOutService.editpurinAjax(sellOutPO);

        return result;
    }

    /**
     * 销售库单审核 界面
     */
    @GetMapping("/auditsellout.do")
    public String auditselloutDo(Long id, Model model) throws CloneNotSupportedException {
        model.addAttribute("title", "采购入库单审核");

        List<SellOutPO> allsort = sellOutService.findAllsort();

        model.addAttribute("sellOutlist", allsort);
        model.addAttribute("selloutstatus", SellOutService.SELLOUT_STATUS_MAP);

        return "stock/sell/auditSellOut";
    }


    /**
     * 跳转到审核出库单界面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/auditeditsellout.do")
    public String auditeditselloutDo(Long id,Model model){
        SellOutPO byId = sellOutService.findById(id);
        model.addAttribute("selloutstatus", SellOutService.SELLOUT_STATUS_MAP);
        model.addAttribute("title","出库单审核");
        model.addAttribute("sellOut",byId);

        return "stock/sell/auditeditSellOut";
    }



    /**
     * ajax 审核出库单
     * @return
     */
    @PostMapping("/auditSellOut.ajax")
    @ResponseBody
    public AjaxResult auditSellOutAjax(@RequestBody SellOutPO sellOutPO){
        /**
         * 0 编制
         * 1 出库
         * 3 废弃
         */
        Long id = sellOutPO.getId();
        Integer status = sellOutPO.getStatus();
        if(ValidateMember.isEmpty(id)||ValidateMember.isEmpty(status)){
            return AjaxResult.fail(500, "数据有误, 请重新检查");
        }

        AjaxResult result = sellOutService.auditSellOutAjax(id, status);
        result.setCode(200);
        result.setMsg(result.getMsg());
        return result;
    }
}
